import sys
import os
import time
import traceback
import pandas as pd

# 添加当前目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

class FunctionTester:
    def __init__(self):
        # 初始化功能测试器
        self.test_log = []
        self.success_count = 0
        self.fail_count = 0
        self.add_log("功能测试器初始化完成")
        
    def add_log(self, message):
        # 添加测试日志
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
        log_message = f"[{timestamp}] {message}"
        self.test_log.append(log_message)
        print(log_message)
    
    def save_log(self, filename="function_test_log.txt"):
        # 保存测试日志到文件
        with open(filename, "w", encoding="utf-8") as f:
            for log in self.test_log:
                f.write(log + "\n")
        self.add_log(f"测试日志已保存到: {filename}")
    
    def test_excel_search_tool(self):
        # 测试Excel搜索工具的核心功能
        try:
            self.add_log("\n=== 开始测试Excel搜索工具核心功能 ===")
            
            # 测试1: 检查Excel搜索工具模块是否能正确导入
            try:
                from excel_search_tool import ExcelSearchTool
                self.add_log("测试1 - 导入模块: 通过")
                self.success_count += 1
            except Exception as e:
                self.add_log(f"测试1 - 导入模块: 失败: {str(e)}")
                self.fail_count += 1
                return
            
            # 测试2: 创建工具实例
            try:
                search_tool = ExcelSearchTool()
                self.add_log("测试2 - 创建工具实例: 通过")
                self.success_count += 1
            except Exception as e:
                self.add_log(f"测试2 - 创建工具实例: 失败: {str(e)}")
                self.fail_count += 1
                return
            
            # 测试3: 检查关键属性
            try:
                # 检查all_results属性
                if hasattr(search_tool, 'all_results') and isinstance(search_tool.all_results, list):
                    self.add_log(f"测试3 - 验证all_results属性: 通过 (类型: {type(search_tool.all_results)})")
                    self.success_count += 1
                else:
                    self.add_log(f"测试3 - 验证all_results属性: 失败 (属性不存在或类型错误)")
                    self.fail_count += 1
                
                # 检查search_text属性
                if hasattr(search_tool, 'search_text'):
                    self.add_log(f"测试3 - 验证search_text属性: 通过")
                    self.success_count += 1
                else:
                    self.add_log(f"测试3 - 验证search_text属性: 失败 (属性不存在)")
                    self.fail_count += 1
                
            except Exception as e:
                self.add_log(f"测试3 - 检查属性时出错: {str(e)}")
                self.fail_count += 1
            
            # 测试4: 检查测试文件是否存在
            test_file = "VBA整合搜索结果_3.xlsx"
            if os.path.exists(test_file):
                self.add_log(f"测试4 - 检查测试文件: 通过 (找到{test_file})")
                self.success_count += 1
            else:
                self.add_log(f"测试4 - 检查测试文件: 失败 (未找到{test_file})")
                self.fail_count += 1
            
            # 测试5: 尝试使用pandas读取测试文件
            try:
                if os.path.exists(test_file):
                    df = pd.read_excel(test_file)
                    self.add_log(f"测试5 - 读取Excel文件: 通过 (成功读取{len(df)}行数据)")
                    self.success_count += 1
                else:
                    self.add_log(f"测试5 - 读取Excel文件: 跳过 (测试文件不存在)")
            except Exception as e:
                self.add_log(f"测试5 - 读取Excel文件: 失败: {str(e)}")
                self.fail_count += 1
            
            # 测试6: 检查可执行文件
            exe_file = "ExcelSearchTool.exe"
            if os.path.exists(exe_file):
                file_size = os.path.getsize(exe_file) / 1024  # KB
                self.add_log(f"测试6 - 检查可执行文件: 通过 ({exe_file}, {file_size:.2f} KB)")
                self.success_count += 1
            else:
                self.add_log(f"测试6 - 检查可执行文件: 失败 (未找到{exe_file})")
                self.fail_count += 1
            
            # 总结测试结果
            self.add_log("\n=== 功能测试总结 ===")
            self.add_log(f"通过测试: {self.success_count}")
            self.add_log(f"失败测试: {self.fail_count}")
            
            if self.fail_count == 0:
                self.add_log("测试结论: 所有测试项目均通过，Excel搜索工具功能正常!")
            else:
                self.add_log(f"测试结论: 发现{self.fail_count}个问题，需要进一步检查和修复。")
            
        except Exception as e:
            self.add_log(f"功能测试过程中发生错误: {str(e)}")
            self.add_log(f"错误堆栈: {traceback.format_exc()}")

if __name__ == "__main__":
    # 创建功能测试器并运行测试
    tester = FunctionTester()
    tester.add_log("=== Excel搜索工具功能测试开始 ===")
    
    # 运行功能测试
    tester.test_excel_search_tool()
    
    # 保存测试日志
    tester.save_log()
    
    tester.add_log("=== Excel搜索工具功能测试结束 ===")